import React, { useState, useEffect } from 'react'
import { Dialog } from 'antd-mobile'
import { Input, Button } from 'antd-mobile'
import { Label } from '@/components/ui/label'

export default function WeightInputDialog({ open, onOpenChange, onSubmit }) {
  const [weight, setWeight] = useState('')
  const [error, setError] = useState('')
  const [success, setSuccess] = useState(false)
  const [submitting, setSubmitting] = useState(false)

  useEffect(() => {
    let dialogKey = null
    if (open) {
      Dialog.show({
        header: '录入今日体重',
        content: (
          <div style={{paddingTop:8}}>
            <Label htmlFor='weight'>体重 (kg)</Label>
            <Input id='weight' placeholder='例如: 70.5' value={weight} onChange={(val)=>{ setWeight(val); setError('') }} />
            {error && <div style={{color:'red', marginTop:8}}>{'⚠ '}{error}</div>}
            {success && <div style={{color:'green', marginTop:8}}>{'✔ 已记录'}</div>}
            {submitting && <div style={{color:'#666', marginTop:8}}>{'… 提交中'}</div>}
          </div>
        ),
        closeOnAction: true,
        actions: [
          [{ key: 'cancel', text: '取消', danger: false }, { key: 'confirm', text: '确定', primary: true }],
        ],
        onAction: (action) => {
          if (action.key === 'confirm') {
            handleSubmit()
          } else {
            onOpenChange(false)
          }
        }
      })
    }

    return () => {
      // cleanup if needed
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, weight, error, success])

  const handleSubmit = () => {
    ;(async ()=>{
      setError('')
      if (!String(weight).trim()) { setError('请输入体重'); return }
      const num = parseFloat(weight)
      if (isNaN(num) || num <= 0 || num > 300) { setError('请输入有效体重 (1-300)'); return }
      setSubmitting(true)
      try {
        const res = await onSubmit(num)
        // res === null means network failed but optimistic update applied
        if (res === null) {
          setSuccess(true)
          setWeight('')
          setTimeout(() => { setSuccess(false); onOpenChange(false) }, 800)
        } else if (res && typeof res === 'object') {
          // server uses { code, message, data, success }
          if (res.success) {
            // try to show server message if any
            const msg = res.message || '已保存到服务器'
            setSuccess(true)
            setWeight('')
            // optionally show message briefly via success area
            setTimeout(() => { setSuccess(false); onOpenChange(false) }, 700)
          } else {
            // not success
            const msg = res.message || '提交失败'
            setError(msg)
          }
        } else if (res && res.error) {
          setError(res.error || '提交失败')
        } else {
          setSuccess(true)
          setWeight('')
          setTimeout(() => { setSuccess(false); onOpenChange(false) }, 600)
        }
      } catch (e) {
        console.error(e)
        setError('提交时发生错误')
      } finally {
        setSubmitting(false)
      }
    })()
  }

  return null
}
